package y_ut.dbtools.imp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import y_ut.dbtools.DBTool;

/**
 * 
 * @author youxz
 *
 */
public class DBDataImport {
private Logger logger = Logger.getLogger(DBDataImport.class);
	
	private DataSource dataSource;
	
	private String driver;
	private String url;
	private String user;
	private String passwd;
	
	public DBDataImport(DataSource dataSource) {
		super();
		this.dataSource = dataSource;
	}
	
	public DBDataImport(String driver, String url, String user, String passwd) {
		super();
		this.driver = driver;
		this.url = url;
		this.user = user;
		this.passwd = passwd;
	}
	
	public boolean Import(IImpReader reader){
		Connection conn = null;
		try{
			reader.open();
			
			if(this.dataSource!=null){
				conn = this.dataSource.getConnection();
			}else{
				conn = DBTool.connectSQL(driver, url, user, passwd);
			}
			Statement state = conn.createStatement();
			while(reader.hasNextTable()){
				String tableName = reader.nextTable();
				String []colNames = reader.getColNames();
				ResultSet rs = state.executeQuery("SELECT * FROM "+tableName+" WHERE 1=2");
				int[] colTypes = DBTool.getColumnTypes(rs,colNames);
				rs.close();
				
				String[] row = null;
				String sql = DBTool.generate(tableName, colNames);
				conn.setAutoCommit(false);
				try{
					
					int rowcount = state.executeUpdate("DELETE FROM "+tableName);
					logger.info("DELETE FROM "+tableName+" delete row count:"+rowcount);
					logger.info(sql);
					PreparedStatement pstate = conn.prepareStatement(sql);
					rowcount= 0;
					while((row = reader.getNextRowData())!=null){
						DBTool.setParams(pstate,colTypes, row);
						pstate.executeUpdate();
						rowcount++;
					}
					logger.info(tableName+" insert row count:"+rowcount);
					conn.commit();
				}catch(Exception e){
					logger.error(e);
					e.printStackTrace();
					conn.rollback();
				}
			}
			state.close();
			return true;
		}catch(SQLException e){
			logger.error(e);
			e.printStackTrace();
		}finally{
			reader.close();
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		return false;
	}
	
	
}
